package org.flown.novel.interceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.flown.novel.controller.SessionAttribute;
import org.flown.novel.data.Author;
import org.flown.novel.data.User;
import org.springframework.lang.Nullable;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.io.PrintWriter;


/**
 * 拦截一些没登录的请求
 * */
public class LoginInterceptor implements HandlerInterceptor
{

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception
    {
        String servlet_path = request.getServletPath();

        HttpSession session = request.getSession();
        User user = (User)session.getAttribute(SessionAttribute.USER.getName());
        Author author = (Author)session.getAttribute(SessionAttribute.AUTHOR.getName());

        if (servlet_path.contains("/upload")
            || servlet_path.contains("/update")
            || servlet_path.contains("/delete"))
            return false;

        if (servlet_path.contains("/publishBook") && author == null)
        {
            PrintWriter out = response.getWriter();
            out.println("作者未登录");
            out.close();
            return false;
        }
        if (servlet_path.contains("/author/register") && author != null)
        {
            PrintWriter out = response.getWriter();
            out.println("你已经是作者了");
            out.close();
            return false;
        }
        if (author != null)
            return true;

        if (servlet_path.contains("/author/register") && user == null)
        {
            PrintWriter out = response.getWriter();
            out.println("你还未登录，无法请求该页面");
            out.close();
            return false;
        }

        return true;
    }


    @Override
    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response,
                           Object handler,
                           @Nullable ModelAndView modelAndView)
            throws Exception
    {

    }


    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response,
                                Object handler,
                                @Nullable Exception ex)
            throws Exception
    {

    }
}
